﻿#Requires AutoHotkey v2.0

#Include ../_lib/Extend.ahk
#Include ../_lib/RunCMD.ahk
#Include ../_lib/Theme.ahk
#Include ../_lib/util/Lerp.ahk

SetTimer (*) => DoToast(false), 60 * 1e3

tray := A_TrayMenu
  , tray.delete()
  , tray.Add('Check', (*) => DoToast())
  , tray.Add('Reload', (*) => Reload())
  , tray.Add('Exit', (*) => ExitApp())
  , tray.ClickCount := 1
  , tray.Default := 'Check'

DoToast(force := true, *) {
  r := GetBatteryChargeRemaining()
  if force or r < 70
    ToastCommon('电池剩余电量', r, 5000, GetTheme(Number(r)))
}

GetTheme(r) {
  switch {
    case r >= 70: return Safe()
    case r >= 50: return Warn()
    case r >= 30: return Danger()
    default: return Dead()
  }
}

class Safe extends Theme.Themes {
  __New() {
    super.__New()
    this.window_Bgc := '#1D2021', this.default_Fc := '#ffcc01'
  }
}

class Warn extends Theme.Themes {
  __New() {
    super.__New()
    this.window_Bgc := '#E6FF31', this.default_Fc := '#353a0e'
  }
}

class Danger extends Theme.Themes {
  __New() {
    super.__New()
    this.window_Bgc := '#FF9826', this.default_Fc := '#4f300c'
  }
}

class Dead extends Theme.Themes {
  __New() {
    super.__New()
    this.window_Bgc := '#FF2011', this.default_Fc := '#ffffff'
  }
}

ToastCommon(str, content, period, _theme) {

  g := Gui('+AlwaysOnTop +ToolWindow -Caption +Border')
  g.MarginX := g.MarginY := 0
  g.SetFont('s14', 'consolas')

  title := g.AddText('x5 y5 Wrap', str)
  title.GetPos(, , &w)

  g.AddText('x5 y+5 right w' w, content).SetFont('bold')

  g.AddText('x0 y+5 Backgroundffd500 h2 w' w + 20)

  g.OnEvent('ContextMenu', (*) => _checked := true)
  Theme.Custom(g, _theme)

  g.Show('Hide'), g.GetPos(, , &w, &h)
  p := g.AddText('x0 y' h - 4 ' Backgroundff2323 h3 w' w)
  g.Move(A_ScreenWidth, 0), g.Show('NA')

  curTime := A_TickCount
  duration := 1500, dist := A_ScreenWidth - w
  t := 200, a := period, _checked := false

  SetTimer fn, 1

  fn(*) {
    g.Move(Floor(Lerp(A_ScreenWidth, dist, bounceOut((A_TickCount - curTime) / duration))))
    if A_TickCount - curTime >= duration {
      SetTimer fn, 0
      g.Move(dist)
      loop t {
        if _checked
          break
        p.Move(, , w - (w / t) * A_Index)
        Sleep a / t
      }
      curTime := A_TickCount
      SetTimer exitFn, 1
    }

    exitFn(*) {
      g.Move(Floor(Lerp(dist, A_ScreenWidth, easeOut((A_TickCount - curTime) / duration))))
      if A_TickCount - curTime >= duration {
        SetTimer exitFn, 0
        g.Destroy()
      }
    }
  }

}

GetBatteryChargeRemaining() {
  batteryCmd := 'powershell -Command "Get-CimInstance -ClassName Win32_Battery | Select-Object EstimatedChargeRemaining"'

  r := RunCMD(batteryCmd)
  r := LTrim(SubStr(r, 49))
  return r
}